//
//  ViewController.m
//  19-CarHomeWork
//
//  Created by 曹曹 on 16/8/9.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "ViewController.h"
#import "GXList.h"
#import "GXResult.h"
#import "GXCarHome.h"
#import "GXBrandlist.h"
#import "CarTableViewCell.h"
#import "UIImageView+DownloadImage.h"
#import "CCList.h"
#import "CCResult.h"
#import "CCMetalist.h"
#import "CCChooseCar.h"
#import "ChooseTableViewCell.h"
#import "MainCarTableViewCell.h"
#import "HotBrandTableViewCell.h"
#import "StarTableViewCell.h"
#import "CGXList.h"
#import "CGXHotCar.h"
#import "CGXResult.h"
#import "GGList.h"
#import "GGResult.h"
#import "GGMainCar.h"

#define kHotDataURL @"http://cars.app.autohome.com.cn/dealer_v6.0.0/dealer/hotbrands-pm1.json"
#define kMainDataURL @"http://adnewnc.app.autohome.com.cn/autov5.7.0/ad/infoad.ashx?appid=2&platform=1&version=6.2.0&networkid=0&adtype=1&provinceid=110000&lng=121.550888&lat=38.889660&pageindex=1&deviceid=d1ecb940123d620cb05a1b2b0a00da8bdd5e4fbe&idfa=981CD0F4-F1F0-4D0F-9C5E-58280F40E4B0&devicebrand=apple&devicemodel=iPhone&gps_city=210200&pageid=d1ecb940123d620cb05a1b2b0a00da8bdd5e4fbe1470913307169&isretry=0"
#define kChoseDataURL @"http://cars.app.autohome.com.cn/cars_v5.8.0/cars/getmarks-a2-pm1.json"
#define kAllCarDataURL @"http://app.api.autohome.com.cn/autov4.6/cars/brands-a2-pm2-v4.6.1-ts635580073583652962.html"

@interface ViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) NSMutableArray *brandArray;
@property (nonatomic, strong) NSMutableArray *metalistArray;
@property (nonatomic, strong) NSMutableArray *choseListArray;
@property (nonatomic, strong) CGXHotCar *hot;
@property (nonatomic, strong) GGMainCar *main;
@property (nonatomic, strong) CCChooseCar *chose;
@property (nonatomic, strong) GXCarHome *carHome;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 网络请求
    [self getSyncDatafromURL:kAllCarDataURL];
    [self getSyncDatafromURL:kHotDataURL];
    [self getSyncDatafromURL:kMainDataURL];
    [self getSyncDatafromURL:kChoseDataURL];
    
    // JSON解析
    //    [self hotCarData];
    //    [self handleMainData];
    //    [self handleChooseCar];
    //    [self handleData];
}
#pragma mark -
- (id) getContainerForResource:(NSString *)resource type:(NSString *)type {
    NSString *carPath = [[NSBundle mainBundle] pathForResource:resource ofType:type];
    NSData *carData = [NSData dataWithContentsOfFile:carPath];
    NSError *error = nil;
    return [NSJSONSerialization JSONObjectWithData:carData options:NSJSONReadingMutableContainers error:&error];
}
#pragma mark - request
- (void)getSyncDatafromURL:(NSString *)urlString {
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *hotRequest = [NSMutableURLRequest requestWithURL:url];
    hotRequest.HTTPMethod = @"GET";
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:hotRequest
                                                completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                    dispatch_async(dispatch_get_main_queue(), ^{
                                                        NSError *error = nil;
                                                        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                       options:NSJSONReadingMutableContainers
                                                                         error:&error];
                                                        NSArray *listArray = dictionary[@"result"][@"list"];
                                                        if (dictionary[@"result"][@"brandlist"]) {
                                                            self.carHome = [GXCarHome modelWithDictionary:dictionary];
                                                            [self.tableView reloadData];
                                                        } else if (listArray.count == 10) {
                                                            self.hot = [CGXHotCar modelWithDictionary:dictionary];
                                                            [self.tableView reloadData];
                                                        } else if (listArray.count == 3) {
                                                            self.main = [GGMainCar modelWithDictionary:dictionary];
                                                            [self.tableView reloadData];
                                                        } else if (dictionary[@"result"][@"metalist"]) {
                                                            self.chose = [[CCChooseCar alloc] initWithDictionary:dictionary];
                                                            [self.tableView reloadData];
                                                        }
                                                    });
                                                }];
    [dataTask resume];
}
#pragma mark - all
- (void)handleData {
    NSDictionary *carDictionary = [self getContainerForResource:@"AllCar" type:@"json"];
    // carHome
    GXCarHome *carHome = [[GXCarHome alloc] initWithDictionary:carDictionary];
    NSDictionary *resultDictionary = carDictionary[@"result"];
    // result
    GXResult *result = [[GXResult alloc] initWithDictionary:resultDictionary];
    NSArray *brandlist = resultDictionary[@"brandlist"];
    self.brandArray = [NSMutableArray array];
    for (NSDictionary *brandlistDictionary in brandlist) {
        GXBrandlist *brandlist = [[GXBrandlist alloc] initWithDictionary:brandlistDictionary];
        NSArray *list = brandlistDictionary[@"list"];
        self.listArray = [NSMutableArray array];/**< list */
        for (NSDictionary *dictionary in list) {
            GXList *list = [[GXList alloc] initWithDictionary:dictionary];
            [_listArray addObject:list];
        }
        brandlist.list = [NSArray arrayWithArray:_listArray];
        [_brandArray addObject:brandlist];
    }
    result.brandlist = [NSArray arrayWithArray:_brandArray];/**< brand */
    carHome.result = result;
}
#pragma mark - ChooseCar
- (void)handleChooseCar {
    NSDictionary *chooseDictionary = [self getContainerForResource:@"ChoseCar" type:@"json"];
    CCChooseCar *chooseCar = [[CCChooseCar alloc] initWithDictionary:chooseDictionary];
    NSDictionary *resultDictinary = chooseDictionary[@"result"];
    CCResult *result = [[CCResult alloc] initWithDictionary:resultDictinary];
    chooseCar.result = result;
    NSArray *metalistArray = resultDictinary[@"metalist"];
    self.metalistArray = [NSMutableArray array];
    for (NSDictionary *dictionary in metalistArray) {
        CCMetalist *metalist = [[CCMetalist alloc] initWithDictionary:dictionary];
        [_metalistArray addObject:metalist];
        NSArray *listArray = dictionary[@"list"];
        self.choseListArray = [NSMutableArray array];
        for (NSDictionary *listDictionary in listArray) {
            CCList *list = [[CCList alloc] initWithDictionary:listDictionary];
            [_choseListArray addObject:list];
        }
        metalist.list = [NSArray arrayWithArray:_choseListArray];
        [_metalistArray addObject:metalist];
    }
}
#pragma mark - HotCar
- (void)hotCarData {
    NSDictionary *dictionary = [self getContainerForResource:@"HotBrand" type:@"json"];
    self.hot = [CGXHotCar modelWithDictionary:dictionary];
}
#pragma mark - MainData
- (void)handleMainData {
    NSDictionary *dictionary = [self getContainerForResource:@"Extension" type:@"json"];
    self.main = [GGMainCar modelWithDictionary:dictionary];
}
#pragma mark - sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _carHome.result.brandlist.count + 4;
}
#pragma mark - rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 1;
    } else if ( section == 2) {
        return 1;
    } else if (section == 3) {
        return 1;
    } else {
        return self.carHome.result.brandlist[section - 4].list.count;
    }
}
#pragma mark - cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        StarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"star"];
        return cell;
    } else if (indexPath.section == 1) {
        HotBrandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hot"];
        cell.list = _hot.result.list;
        return cell;
    } else if (indexPath.section == 2) {
        MainCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"main"];
        cell.list = _main.result.list;
        return cell;
    } else if (indexPath.section == 3) {
        ChooseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chose"];
        cell.list = _chose.result.metalist[0].list;
        return cell;
    }
    CarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    cell.list = _carHome.result.brandlist[indexPath.section - 4].list[indexPath.row];
    return cell;
}
#pragma mark - 索引栏
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *array = [NSMutableArray array];
    [array addObject:@"⭐️"];
    [array addObject:@"热"];
    [array addObject:@"主"];
    [array addObject:@"选"];
    for (GXBrandlist *brand in self.carHome.result.brandlist) {
        [array addObject:brand.letter];
    }
    return array;
}
#pragma mark - 头视图标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return nil;
    } else if (section == 1) {
        return @"热门品牌";
    } else if (section == 2) {
        return @"主打车";
    } else if (section == 3) {
        return @"选车神器";
    }
    return _carHome.result.brandlist[section - 4].letter;
}
#pragma mark - 
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section > 3) {
        return nil;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 30)];
    view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:0.5];
    return view;
}
#pragma mark - 头视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0 || section > 3) {
        return 0;
    } else {
        return 30;
    }
}
#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 70;
    } else if (indexPath.section == 1) {
        return 180;
    } else if (indexPath.section == 2) {
        return 120;
    } else if (indexPath.section == 3) {
        return 100;
    } else {
        return 44;
    }
}
#pragma mark - Other
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
